   (function($) {

       function calendarWidget(el, params) {
           el.empty();
           //是否打开了leftBar,深度关联于html中sidebar的命名"leftBar"
           var leftOpen = $('#leftBar').sidebar('is open');
           //remove related handlders and dom elements;
           var now = new Date();
           var thismonth = now.getMonth();
           var thisyear = now.getYear() + 1900;

           var opts = {
               month: thismonth,
               year: thisyear,
               validTimeList: [], //合法的时间列表,其他的时间列为disabled
               queryDataTimes: [], //查询的时间
               statusTimeList: [] //工况时间列表
           };

           $.extend(opts, params);

           var queryDataTimes = opts.queryDataTimes;
           var monthNames = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
           var dayNames = ['日', '一', '二', '三', '四', '五', '六'];
           var month = i = parseInt(opts.month);
           var year = parseInt(opts.year);
           var nxtmonth, nxtyear = year,
               premonth, preyear = year;

           if (month === 11) {
               nxtmonth = 0;
               nxtyear = year + 1;

           } else {
               nxtmonth = month + 1;
           }
           if (month === 0) {
               premonth = 11;
               preyear = year - 1;
           } else {
               premonth = month - 1;
           }

           //合法的,可以点击的天数,如[1,12,22,31];
           var validDays = [];
           //在本月范围内的,工况时间表,如[{status:'开挖',time:'2012-01-01'}]
           var validStatusDays = [];
           (function() { //filter valid dates
               var timeList = opts.validTimeList.map(function(item) {
                   var splits = item.split('-'); //默认是这个yyyy-MM-dd格式,其他的暂时不支持
                   return {
                       year: parseInt(splits[0]),
                       month: parseInt(splits[1]),
                       day: parseInt(splits[2])
                   };
               });

               validDays = timeList.filter(function(item) {
                   return item.year === year && item.month === month + 1;
               }).map(function(item) {
                   return item.day;
               });

               var validStatusDaysInYMD = opts.statusTimeList.map(function(item) {
                   var splits = item.time.split('-'); //默认是这个yyyy-MM-dd格式,其他的暂时不支持
                   return {
                       year: parseInt(splits[0]),
                       month: parseInt(splits[1]),
                       day: parseInt(splits[2]),
                       status: item.status
                   };
               });
               validStatusDays = validStatusDaysInYMD.filter(function(item) {
                   return item.year === year && item.month === month + 1;
               }).map(function(item) {
                   return {
                       day: item.day,
                       status: item.status
                   };
               });
           })();



           var table = '<div id="calendar">';

           table += '<div id="calendar-top" class="inverted ui fluid three item menu"><a id="calendar-pre-icon" class="item"><i  class="left arrow icon"></i></a><span class="item " id="calendar-text">' + year + '-' + monthNames[month] + '</span><a  id="calendar-next-icon" class="item"><i  class="right arrow icon"></i></a></div>';

           //table += ('<div id="current-month" class="ui inverted centered">' + year + '-' + monthNames[month] + '</div>');
           table += ('<div class="ui seven column  grid" ' + 'id="calendar-month">');

           table += '<div  class="row" id="calendar-head">';



           for (d = 0; d < 7; d++) {
               table += '<div class="column"><span class="ui item">' + dayNames[d] + '</span>' + '</div>';
           }

           table += '</div>';

           var days = getDaysInMonth(month, year);
           var firstDayDate = new Date(year, month, 1);
           var lastDayDate = new Date(year, month, days);
           var firstDay = firstDayDate.getDay();
           var lastDay = lastDayDate.getDay();
           var prev_m = month == 0 ? 11 : month - 1;
           var prev_y = prev_m == 11 ? year - 1 : year;
           var prev_days = getDaysInMonth(prev_m, prev_y);
           firstDay = (firstDay == 0 && firstDayDate) ? 7 : firstDay;
           var i = 0;
           var startJ = 0,
               endJ = 35;
           table += '</div>';

           table += '<div id="calendar-day-pane" class="ui seven column  grid">';
           for (var j = startJ; j < endJ; j++) {
               if (j % 7 === 0) table += ('<div  class="row">');
               if ((j < firstDay)) {
                   table += ('<div class="column menu inverted ui"><a class="ui item disabled">' + (prev_days - firstDay + j + 1) + '</a></div>');
               } else if ((j >= firstDay + getDaysInMonth(month, year))) {
                   i = i + 1;
                   table += ('<div class="column menu inverted ui"><a class="ui item disabled">' + i + '</a></div>');
               } else {
                   var curDay = j - firstDay + 1;
                   var curDayStr = curDay < 10 ? ('0' + curDay.toString()) : curDay.toString();

                   //这一天在不在当月的工况天里
                   var curStatusDay = validStatusDays.filter(function(item) {
                       return item.day === curDay;
                   });
                   var smallScreen = document.documentElement.clientWidth < 1025 ? true : false;
                   var statusStyle = smallScreen ? 'style="max-width: 3rem;text-overflow: ellipsis;overflow: hidden;"' : 'text-overflow: ellipsis;overflow: hidden;"';

                   var statusStr = "";
                   if (curStatusDay.length > 0) {
                       if (smallScreen) {
                           statusStr = "况";
                       } else {
                           statusStr = curStatusDay[0].status;
                       }
                   }
                   //判断日期是否包含在可用日期列表中
                   if (validDays.indexOf(curDay) >= 0) {
                       var dataDate = year + '-' + monthNames[month] + '-' + curDayStr;
                       var aAttr = 'data-date="' + dataDate + '" ';
                       var spanAttr = (j % 7 === 6) && !leftOpen ? 'data-position="left center"' : '';

                       if (curStatusDay.length > 0) {
                           //将天数文字替换成工况描述
                           var aClass = queryDataTimes.indexOf(dataDate) >= 0 ? "ui  red  label" : "ui  teal  label"; //
                           table += ('<div class="column valid-day" style="white-space:nowrap;"  title="' + curStatusDay[0].status + '"><a ' + statusStyle + ' class="' + aClass + '" ' + aAttr + '><span ' + spanAttr + '>' + statusStr + '</span></a></div>');
                       } else {
                           //照常写入数字
                           var aClass = queryDataTimes.indexOf(dataDate) >= 0 ? "ui  red circular label" : "ui  teal circular label"; //
                           table += ('<div class="column valid-day"><a class="' + aClass + '" ' + aAttr + '><span ' + spanAttr + '>' + curDayStr + '</span></a></div>');
                       }

                   } else {
                       //不包含在列表中
                       if (curStatusDay.length > 0) {
                           table += ('<div class="column menu inverted ui" title="' + curStatusDay[0].status + '" style="white-space:nowrap;"><span ' + statusStyle + ' class="ui item">' + statusStr + '</span></div>');
                       } else {
                           table += ('<div class="column menu inverted ui"><span class="ui item">' + curDayStr + '</span></div>');
                       }
                   }


               }
               if (j % 7 == 6) table += ('</div>');
           }

           table += ('</div></div>');

           el.html(table);

           var pop = null; //追踪popup,一个calendar只能产生一个popup实例
           el.find('.valid-day>.label').on('click', function(event) {
               var maxLength = 4; //最多只能选4个日期,多了会乱,且难以分辨
               var date = $(this).attr('data-date');
               var index = queryDataTimes.indexOf(date);
               if (index >= 0) {
                   //是删除
                   $(this).removeClass('red').addClass('teal');
                   queryDataTimes.splice(index, 1);
               } else {
                   //是新增
                   if (queryDataTimes.length === maxLength) {
                       //最多只能选4个日期
                       return;
                   }
                   var el = $(this).removeClass('teal').addClass('red');
                   queryDataTimes.push(date);
                   var offSet = parseInt($('body').css('margin-left'));

                   $(document).off('click', "**"); //移除绑定的函数

                   //如果是新增了一个日期
                   if (queryDataTimes.length >= 2) {
                       event.stopPropagation();
                       if (pop) {
                           pop.popup('hide');
                       }
                       var hintStr = (maxLength - queryDataTimes.length) > 0 ? '<p> 最多还能再选择<strong class="ui red header">' + (maxLength - queryDataTimes.length).toString() + '</strong>个日期 </p>' : '<p>请点击按钮完成查询</p>';
                       if (opts.onClick) {
                           // children().eq(0).
                           pop = $(this).popup({
                               html: '<div>' + hintStr + '<a class="ui calendar-pop red button small">查询</a></div>',
                               on: 'focus',
                               offset: -offSet
                           }).popup('show');
                           $('.calendar-pop').on('click', (function() {
                               return function(event) {
                                   $.extend(event, {
                                       clickDates: queryDataTimes
                                   });
                                   setTimeout(function() {
                                       queryDataTimes = [];
                                       $('#calendar-day-pane').find('.red').removeClass('red').addClass('teal');
                                       opts.onClick(event);
                                   }, 300);
                               };
                           })(event));

                       }
                   } else if (queryDataTimes.length === 1) {
                       event.stopPropagation();
                       // children().eq(0)
                       pop = $(this).popup({
                           html: '<div><p>选择更多的日期</p><p>还能选择<strong class="ui red header">&nbsp;3&nbsp;</strong>个</p></div>',
                           on: 'focus',
                           offset: -offSet
                       }).popup('show');
                   }

                   $(document).one('click', function(e) {
                       if (pop) {
                           pop.popup('hide all');
                       }
                   });
               }
           });

           $('#calendar-pre-icon').on('click', function() {
               $.extend(opts, {
                   month: premonth,
                   year: preyear,
                   queryDataTimes: queryDataTimes
               });
               //$(el).popup('hide all');
               calendarWidget(el, opts);
           });
           $('#calendar-next-icon').on('click', function() {
               $.extend(opts, {
                   month: nxtmonth,
                   year: nxtyear,
                   queryDataTimes: queryDataTimes
               });
               //$(el).popup('hide all');
               calendarWidget(el, opts);
           });

       }

       function findIndexInQueryDatesArray(array, date) {
           var index = -1;
           for (var i = 0; i < array.length; i++) {
               if (array[i].date === date) {
                   index = i;
                   break;
               }
           }
           return index;
       }

       function getDaysInMonth(month, year) {
           var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
           if ((month == 1) && (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
               return 29;
           } else {
               return daysInMonth[month];
           }
       }


       // jQuery plugin initialisation
       $.fn.calendarWidget = function(params) {
           calendarWidget(this, params);
           return this;
       };

   })(jQuery);
